
#include "nrf_drv_spi.h"

#define AT45DB04 1

#if AT45DB04

#define DEBUG 0

#if DEBUG

#define PAGE_SIZE 256
#define NUM_PAGES 20
#define PAGE_HEAD_SIZE 16
#define PAGE_DATA_SIZE 24
#define PAGE_HALF_SIZE (PAGE_SIZE >> 1)

#else

#define PAGE_SIZE 256
#define NUM_PAGES 2048
#define PAGE_HEAD_SIZE 16
#define PAGE_DATA_SIZE 240
#define PAGE_HALF_SIZE (PAGE_SIZE >> 1)

#endif

#define META_BLOCK_ID 0
#define DATA_BLOCK_START_ID 1
#define TOTAL_BLOCK_NUM NUM_PAGES

#define SECTOR_MAGIC 0xABABBABA
#define HEADER_MAGIC 0xDEADDEAD

#endif

struct meta_block {
    uint32_t magic;
    uint32_t nrf_device_id;
    uint32_t meta_block_id;
    uint32_t data_block_start_id;
    uint32_t data_block_curr_id;
    uint32_t data_block_total_count;

    int8_t adc_buffer_id;      // 0 or 1
    int8_t flash_buffer_id;
};

struct data_block {
    uint32_t magic;
    uint32_t timestamp;
    uint8_t interval;
    uint8_t idx;
    uint8_t cnt;
    uint8_t padding[5];
    uint8_t data[PAGE_DATA_SIZE];
};

struct flash_ctx_t {
    nrf_drv_spi_t *spi;
};

extern volatile struct meta_block meta_info;
extern volatile struct data_block data_double_buffer[2];

uint32_t flash_init_ctx(struct flash_ctx_t *ctx, uint8_t spi_id);
uint32_t flash_get_id(struct flash_ctx_t *ctx);
uint32_t flash_test(struct flash_ctx_t *ctx);
uint32_t flash_write_page(struct flash_ctx_t *ctx, int32_t page_id, uint8_t *dat, uint32_t len);
uint32_t flash_read_page(struct flash_ctx_t *ctx, int32_t page_id, uint8_t *dat, uint32_t len);
uint8_t flash_check_busy(struct flash_ctx_t *ctx);
void flash_erase_chip(struct flash_ctx_t *ctx);
uint32_t flash_init_meta_info(struct flash_ctx_t *ctx, uint8_t *buf, uint32_t len);
void flash_init_data_info(struct data_block *block, uint32_t ts, uint8_t interval);


struct data_block *get_curr_data_block();
void change_adc_buffer_id();
